package client_service_controller;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import tagsFilesClientDataBase.TagFilesDB;

import client_listen_update_files.ConfigManager;
/**
 * Service that run in background include options to start and stop the service  
 * @author Orit and Yoav
 *
 */
public class WatchDirService {

	//-- static instance of the service class--//
	private static WatchDirService serviceInstance = new WatchDirService();
	
	private boolean stopped = false; //-- flag - if service instance has stopped--// 

	/* 
	 * the method from which tomcat will start/stop the service 
	 */
	public static void windowsService(String args[]) throws MalformedURLException, IOException {
		String cmd = "start";
		if(args.length > 0) cmd = args[0];

		if("start".equals(cmd))  serviceInstance.start();
		else serviceInstance.stop();
	}
	// starts the service instance
	public void start() throws MalformedURLException, IOException {
		final int minute=60000;
		stopped = false;
		System.out.println();
		System.out.println("My Service Started "+ new java.util.Date());
		int count=0;
		while(!stopped) {
			//doDownloadForToday(count);
			synchronized(this) {
				try {
					this.wait(15*minute);  // wait 5 minutes
					count++;
				}
				catch(InterruptedException ie){}
			}
		}
		System.out.println("My Service Finished " + new java.util.Date());
	}

	//Stops this service instance
	public void stop() {
		stopped = true;
		synchronized(this) {
			this.notify();
		}
	}

	private void doDownloadForToday(int count) throws MalformedURLException, IOException {
		System.out.println("111");
		String dates[]= {"2011-04-14","2010-02-27","2009-01-01"};

		//important for future:
		//String endDate=getTodayAsString();
		if (count<dates.length){
			System.out.println("222");
			String endDate=dates[count];
			String startDate = getShilshomAsString(endDate);
			System.out.println("333");
			System.out.println("start: "+startDate+", end: "+endDate);

			List<String> hdfURLs = new ArrayList<String>();//getFilesBetweenDates(startDate, endDate);
			//hdfURLs.add("http://bdonline.sqe.com/documents/testplans.pdf");
			hdfURLs.add("ftp://e4ftl01.cr.usgs.gov/MODIS_Dailies_E/MOLT/MOD11A1.005/2011.04.12/MOD11A1.A2011102.h20v05.005.2011103221754.hdf");
			System.out.println(hdfURLs.size()+" URL's");
			//System.out.println("first: "+hdfURLs.get(0));
			//System.out.println("second: "+hdfURLs.get(1));
			//System.out.println("third: "+hdfURLs.get(2));
			downloadFilesToWorkspace(hdfURLs);
		}
	}

	private static List<String> getFilesBetweenDates(String startDate, String endDate) {

		String url ="https://api.echo.nasa.gov/echo-esip/search/granule.html?clientId=esip-html-client&shortName=MOD11A1&versionId=5&dataCenter=LPDAAC_ECS&boundingBox=32%2C35%2C32.1%2C35.1&startTime="+startDate+"T15%3A42%3A11%2B03%3A00&endTime="+endDate+"T15%3A42%3A30%2B03%3A00";
		URL nasa = null;
		try {
			nasa = new URL(url);
		} catch (MalformedURLException e) {e.printStackTrace();}
		URLConnection yc = null;
		try {
			yc = nasa.openConnection();
		} catch (IOException e) {e.printStackTrace();}
		BufferedReader in = null;
		try {
			in = new BufferedReader(	new InputStreamReader(yc.getInputStream()));
		} catch (IOException e) {System.out.println("Can't open web file, server unavailable");e.printStackTrace();}
		List<String> hdfURLs=new ArrayList<String>();
		String inputLine;

		//System.out.println("444");

		try {
			while ((inputLine = in.readLine()) != null){ 
				//System.out.println("555");
				if (inputLine.contains("ftp") && inputLine.contains("Link to data")){
					//System.out.println("666");
					int beginIndex= inputLine.indexOf("ftp");
					int endIndex=inputLine.indexOf("Link to data")-2;
					hdfURLs.add(inputLine.substring(beginIndex, endIndex));
					//System.out.println(inputLine);
				}
			}
		} catch (IOException e) {e.printStackTrace();}
		try {
			in.close();
		} catch (IOException e) {e.printStackTrace();}
		return hdfURLs;
	}

	private static void downloadFilesToWorkspace(List<String> hdfURLs) throws MalformedURLException, IOException {
		for (int i=0 ; i<hdfURLs.size() ; i++){

			String finalURL=hdfURLs.get(i);

			int slashIndex =finalURL.lastIndexOf('/');
			String fileName=finalURL.substring(slashIndex + 1);
			java.io.BufferedInputStream in = null;
			
			try {
				in = new java.io.BufferedInputStream(new  java.net.URL(finalURL).openStream());
			} catch (MalformedURLException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}
			
			int BUFF_SIZE = 1024;
			byte[] buffer = new byte[BUFF_SIZE];
			File fileHdf = new File("C:\\Users\\ori\\Desktop\\", fileName); 
			FileOutputStream fos = new FileOutputStream(fileHdf);
			java.io.BufferedOutputStream bout = new BufferedOutputStream(fos,1024);
			int byteCount = 0;
			try {
				do {
					byteCount = in.read(buffer);
					if (byteCount == -1)
						break;
					bout.write(buffer, 0, byteCount);
					bout.flush();
				} while (true);
			}catch (Exception excp) {excp.printStackTrace(); } 
			finally {bout.close(); in.close();}
			System.out.println("Download suceed");
			/*
			System.out.println("Result no. "+(i+1)+" is: "+hdfURLs.get(i));
			String finalURL=hdfURLs.get(i);
			System.out.println("444, URL: "+finalURL);
			java.io.BufferedInputStream in = null;
			try {
				in = new java.io.BufferedInputStream(new  java.net.URL(finalURL).openStream());
			} catch (MalformedURLException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}
			System.out.println("555");
			int slashIndex =finalURL.lastIndexOf('/');
			String fileName=finalURL.substring(slashIndex + 1);
			java.io.FileOutputStream fos = new java.io.FileOutputStream("C:\\Users\\ori\\Desktop\\"+fileName);
			System.out.println("666: "+fileName);
			java.io.BufferedOutputStream bout = new BufferedOutputStream(fos,1024);

			byte[] data = new byte[1024];
			int x=0;
			while((x=in.read(data,0,1024))>=0)
				bout.write(data,0,x);

			System.out.println("Download suceed");//, "+count+" bytes downloaded");
			bout.close();
			in.close();
			 */
		}

	}

	private static String getDateFromURL(String url) {
		int beginIndex =url.indexOf("005/2");
		String date=new String(url.substring(beginIndex+15, beginIndex+56));
		//date = date.replace('.', '-');
		//System.out.println("C:\\Users\\ori\\Desktop\\"+date+".hdf");
		return date;
	}

	private static String getShilshomAsString(String userDate) {

		DateFormat df= new SimpleDateFormat("yyyy-MM-dd");
		Date today = null;
		try {
			today = df.parse(userDate);
		} catch (ParseException e) {e.printStackTrace();}
		Calendar cal=Calendar.getInstance();
		cal.setTime(today);
		cal.add(Calendar.DAY_OF_YEAR, -2);
		int shilshomDay   = cal.get(Calendar.DATE);
		int shilshomMonth = cal.get(Calendar.MONTH)+1;
		int shilshomYear  = cal.get(Calendar.YEAR);
		if (shilshomDay<10 && shilshomMonth<10)
			return (shilshomYear+"-0"+shilshomMonth+"-0"+shilshomDay);
		else if (shilshomDay<10)
			return (shilshomYear+ "-"+shilshomMonth+"-0"+shilshomDay);
		else if (shilshomMonth<10)
			return (shilshomYear+"-0"+shilshomMonth+"-" +shilshomDay);
		return (shilshomYear+"-"+shilshomMonth+"-"+shilshomDay);
	}
}
